#include "sroverviewwidget.h"

#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QTableView>
#include <QHeaderView>
#include <QStandardItemModel>
#include <QResizeEvent>
#include <QDebug>
#include <QSpinBox>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>

#include <srdatabase.h>

#include "srtransactionwidget.h"

SROverviewWidget::SROverviewWidget(QWidget *parent) : QWidget(parent),
    iPageNum_(0)
{
    QVBoxLayout* layout = new QVBoxLayout();
    QHBoxLayout* layout_statistics = new QHBoxLayout();
    QHBoxLayout* layout_bottom = new QHBoxLayout();
    boxPageNum_ = new QSpinBox();
    labAuditSum_ = new QLabel("今日审核数 <b style='color:red'>0</b>");
    labAuditSum_->setObjectName("今日审核数 <b style='color:red'>%1</b>");
    labMoneySum_ = new QLabel("今日出账总金额 <b style='color:red'>0</b>");
    labMoneySum_->setObjectName("今日出账总金额 <b style='color:red'>%1</b>");

    labLogCount_ = new QLabel("记录总数： <b style='color:red'>0</b>");
    labLogCount_->setObjectName("记录总数： <b style='color:red'>%1</b>");
    QPushButton* btn_update = new QPushButton(tr("更新"));
    tableView_ = new QTableView();

    tableView_->setGeometry(0,0,400,250);
    model_ = new QStandardItemModel();
    tableView_->setModel(model_);

    // model 初始化
    model_->setColumnCount(3);
    model_->setHeaderData(0,Qt::Horizontal, tr("时间"));
    model_->setHeaderData(1,Qt::Horizontal, tr("操作日志"));
    model_->setHeaderData(2,Qt::Horizontal, tr("操作人"));
#ifdef QT_DEBUG
    for(int i = 0; i < 10; ++i)
    {

        model_->setItem(i, 0, new QStandardItem("2017年11月11日 13:41:00"));
        model_->setItem(i, 1, new QStandardItem("这是一个不可以编辑的操作日志，为了方便测试，我这里撰写了非常多的文字"));
        model_->setItem(i, 2, new QStandardItem("admin"));
    }
#else
//    onNextPage(0);
#endif

    // table 初始化
    tableView_->setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
    tableView_->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); // 只能单选
    tableView_->setEditTriggers(QTableView::EditTrigger::NoEditTriggers);
    tableView_->setAlternatingRowColors(true);

    tableView_->setColumnWidth(0, 140);
    tableView_->setColumnWidth(2, 80);
    tableView_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    tableView_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    tableView_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
//    tableView_->resizeColumnToContents(2);



    // 信号链接
    connect(btn_update,&QPushButton::clicked,
            this,&SROverviewWidget::onUpdate);

    connect(tableView_,&QTableView::clicked,
            this, &SROverviewWidget::onClicked);
    connect(boxPageNum_, SIGNAL(valueChanged(int)),
            this, SLOT(onNextPage(int)));
    // 大小
    boxPageNum_->setFixedSize(70,24);
    btn_update->setFixedSize(58,24);
    btn_update->setStyleSheet(QString("font-size:14px;"));

    layout_statistics->addWidget(labAuditSum_);
    layout_statistics->addWidget(labMoneySum_);
    layout_statistics->addWidget(btn_update);
    layout_bottom->addSpacing(20);
    layout_bottom->addWidget(labLogCount_, 0, Qt::AlignLeft);
    layout_bottom->addSpacing(30);
    QLabel* lab_page = new QLabel(tr("页数:"));
    layout_bottom->addWidget(lab_page,0,Qt::AlignLeft);
    layout_bottom->addWidget(boxPageNum_);
    layout_bottom->addStretch();
    layout->addLayout(layout_statistics);
    layout->addWidget(tableView_);
    layout->addLayout(layout_bottom);

    setLayout(layout);
}

void SROverviewWidget::showEvent(QShowEvent *event) {
    // @remark: 若刷新成本高，则利用运行时钟来做刷新约束
    Q_UNUSED(event);
    onUpdate();
}

QString SROverviewWidget::getTodayTotalConsumption(int& out_sum_size)
{
    qlonglong total_consumption = 0;

    // 查询今天所有交易记录
    QList<SRDatabase::stXlsRecord> list_file_data;
    QString begin_time = QDateTime::currentDateTime().toString("yyyy-MM-dd 00:00:00");
    QString end_time = QDateTime::currentDateTime().toString("yyyy-MM-dd 23:59:59");
    SRDatabase::DB()->getXlsTimeRecord(begin_time,end_time,list_file_data);

    out_sum_size = list_file_data.size();

    // 遍历今天所有交易记录的文件夹
    for (auto& data : list_file_data) {

        total_consumption += getFileTotalConsumption(data.sigData);
    }
    return SRTransactionWidget::convertCoin(total_consumption, true);
}

qlonglong SROverviewWidget::getFileTotalConsumption(const QString &_data)
{
    QString analysis_data = SRTransactionWidget::modifyAuditDataValueToString(_data);
    // 解析 data
    qlonglong  vout_sum_money = 0;


    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(analysis_data.toUtf8(), &jsonError);
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) {
        if (doucment.isObject()) {
            QJsonObject object = doucment.object();


            if (object.contains("vin")) {
                QJsonArray vout_arr = object.value("vin").toArray();
                if (!vout_arr.isEmpty()) {
                    int vout_size = vout_arr.size();
                    for (int i = 0; i < vout_size; ++i) {
                        QJsonObject temp_single_vout = vout_arr.at(i).toObject();
                        QString temp_money = "";
                        if (temp_single_vout.contains("value")) {
                            temp_money = temp_single_vout.value("value").toString();
                            vout_sum_money += temp_money.toLongLong();
                        }
                    }
                }
            }

        }
    }


    return vout_sum_money;
}


void SROverviewWidget::onUpdate(void) {
#ifdef QT_DEBUG
    QString temp_audit_num = labAuditSum_->
            objectName().arg(QString::number(rand()%1000));
    QString temp_sum_money = labMoneySum_->
            objectName().arg(QString::number(rand()%1000));

    labAuditSum_->setText(temp_audit_num);
    labMoneySum_->setText(temp_sum_money);
#else
    onNextPage(boxPageNum_->value());
    labLogCount_->setText(labLogCount_->objectName()
                          .arg(SRDatabase::DB()->getOperateLogSize()));
    int i = 0;
    labMoneySum_->setText(labMoneySum_->objectName().arg(getTodayTotalConsumption(i)));
    labAuditSum_->setText(labAuditSum_->objectName().arg(i));


#endif
}

void SROverviewWidget::onClicked(const QModelIndex &_index) {
//    static int last_row = 0;
//    last_row = _index.row();

    tableView_->resizeRowToContents(_index.row());
}

void SROverviewWidget::onNextPage(int _idx) {
    _idx = _idx - 1;
    if (_idx <= 0) {
        boxPageNum_->setValue(1);
        _idx = 0;
    }

    QList<SRDatabase::stLogInfo> list_log;
    const int& row_count = _idx * 20;
    int ret = SRDatabase::DB()->getOperateLog(row_count, row_count + 20, list_log);
    if (ret != 0) {
        qWarning("query operate log failed!");
        return;
    }
    if (list_log.size() == 0) {
        boxPageNum_->setValue(_idx);
        return;
    }


    model_->removeRows(0,model_->rowCount());

    // 设置界面
    int idx = 0;
    for (auto item : list_log) {
        model_->setItem(idx,0, new QStandardItem(item.time));
        model_->setItem(idx,1, new QStandardItem(item.info));
        model_->setItem(idx,2, new QStandardItem(item.name));
        for (int i = 0 ; i < 3; ++i)
            model_->item(idx, i)->setTextAlignment(Qt::AlignCenter);

        ++idx;
    }
}
